import viz
import time
import math
import projector
from time import time
from Action import *
from Gui import *
from VizSoundAction import *
from SimonButtonExtra import *

class Game:
	
	def __init__(self):
		self.simonActionStack = Action() #The correct sequence of actions, determined by simon
		self.myActionStack = Action() #The current sequence of actions that the user has inputed
		self.vrsimon = viz.add('resources/base.dae',pos=[0,0,0])	#place the VRSimon base
		
		self.offset = [0,0.6,-0.33]
		self.range = [0,0.6,-0.33]
		self.scale = 250
	
	def showSequence(self): #Shows simons sequence of actions
		speed = 0.25
		if(len(self.simonActionStack.actionStack) > 5):
			speed -= 0.05
		if(len(self.simonActionStack.actionStack) > 10):
			speed -= 0.05
		if(len(self.simonActionStack.actionStack) > 15):
			speed -= 0.05
		
		self.vrsimon.addAction(vizact.waittime(1))
		self.signal = vizact.signal()
		self.vrsimon.addAction(self.signal.trigger)
		i = 0

		for action in self.simonActionStack.actionStack:
			for button in buttons:
				if button.getNum() == action:
					button.blink(speed)
			
	def addAction(self, action):
		self.myActionStack.addAction(action)
		if self.simonActionStack.compareActions(self.myActionStack) != True:
			self.myActionStack.clearActions()
			self.simonActionStack.clearActions()
			return 0
		elif len(self.simonActionStack.actionStack) == len(self.myActionStack.actionStack):
			self.myActionStack.clearActions()
			self.simonActionStack.addRandomAction()
			return 2
		else:
			return 1



####Kinect Input##################################

def kinectInput():
	if(permissions == 'r'):
		replay()
		return
	kinectHandPosition = handTracker.getPosition()
	kinectHandPosition[0] -= game.offset[0]
	kinectHandPosition[1] -= game.offset[1]
	kinectHandPosition[2] -= game.offset[2]

	calibratedHandPosition = [0,0,0]
	
	calibratedHandPosition[0] = -kinectHandPosition[2]*game.scale + 60 #Front/Back
	calibratedHandPosition[1] = kinectHandPosition[1]*game.scale + 75 #Up/Down
	calibratedHandPosition[2] = kinectHandPosition[0]*game.scale + 60 #Left/Right
	
	handShadow.setPosition(calibratedHandPosition, viz.ABS_GLOBAL)
	
	#print '----'
	#print kinectHandPosition
	#print calibratedHandPosition
	if(permissions == 'w'):
		record()
		return

#vrpn = viz.add('vrpn7.dle')
#handTracker = vrpn.addTracker('Tracker0@localhost', 14)
#vizact.ontimer(0.033,kinectInput)
##################################################



####Keyboard Input################################
def onKeyDown(key):
	if key == viz.KEY_RETURN:
		game.offset = handTracker.getPosition()
	elif key == ' ':
		game.range = handTracker.getPosition()
		game.scale = 60 / ( game.offset[0] - game.range[0] )
		print game.scale
	elif key == 'r':
		game.scale = 250
viz.callback(viz.KEYDOWN_EVENT,onKeyDown)


def keyboardInput():
	global collisionObj
	if(permissions == 'r'):
		replay()
		return
	
	if(viz.key.isDown(viz.KEY_LEFT)):
			handShadow.setPosition(0, 0, 1, viz.REL_PARENT)
	if(viz.key.isDown(viz.KEY_DOWN)):
			handShadow.setPosition(-1, 0, 0, viz.REL_PARENT)
	if(viz.key.isDown(viz.KEY_RIGHT)):
			handShadow.setPosition(0, 0, -1, viz.REL_PARENT)
	if(viz.key.isDown(viz.KEY_UP)):
			handShadow.setPosition(1, 0, 0, viz.REL_PARENT)
	if(viz.key.isDown('d')):
			handShadow.setPosition(0, -1, 0, viz.REL_PARENT)
	if(viz.key.isDown('a')):
			handShadow.setPosition(0, 1, 0, viz.REL_PARENT)
			
		# rotating VR Simon in 3D space	
	# need to add button as vsimon child
	if(viz.key.isDown('h')):						#Left
		game.vrsimon.setAxisAngle( [1,0,0,1], viz.REL_PARENT )
		game.vrsimon.setPosition(0, 0, 0.1, viz.REL_PARENT)
	if(viz.key.isDown('j')):						#Right
		game.vrsimon.setAxisAngle( [-1,0,0,1], viz.REL_PARENT )
		game.vrsimon.setPosition(0, 0, -0.1, viz.REL_PARENT)
	if(viz.key.isDown('u')):						#Up
		game.vrsimon.setAxisAngle( [0,0,-1,1], viz.REL_PARENT )
		game.vrsimon.setPosition(0.1, 0, 0, viz.REL_PARENT)
	if(viz.key.isDown('n')):						#Down
		game.vrsimon.setAxisAngle( [0,0,1,1], viz.REL_PARENT )
		game.vrsimon.setPosition(-0.1, 0, 0, viz.REL_PARENT)
	if(viz.key.isDown('y')):						#move Left
		game.vrsimon.setPosition(0, 0, 1, viz.REL_PARENT)
	if(viz.key.isDown('i')):						#move right
		game.vrsimon.setPosition(0, 0, -1, viz.REL_PARENT)
	if(viz.key.isDown('m')):						#move up
		game.vrsimon.setPosition(1, 0, 0, viz.REL_PARENT)	
	if(viz.key.isDown('b')):						#move right
		game.vrsimon.setPosition(-1, 0, 0, viz.REL_PARENT)				
	if(permissions == 'w'):
		record()
		return

vizact.ontimer(0.025,keyboardInput)
##################################################

####Recoring/Playback#############################

t = (str)(time.time()).replace(".", "")
permissions = 'w'
#outputFile = open("results/" + str(130108201127) + ".txt", permissions)
outputFile = open("results/" + t + ".txt", permissions)

def replay():
	try:
		pos = eval(outputFile.readline())
		handShadow.setPosition(pos[0], pos[1], pos[2], viz.ABS_GLOBAL)
	except SyntaxError:
		return
		
def record():
	outputFile.write(str(handShadow.getPosition()) + "\n")
	return

##################################################



####Collisions####################################
def onCollideBegin(collision):
	for button in buttons:
		if button.vizObject == collision.obj2:
			pressResult = button.press()
			if pressResult == 1:
				pass
			elif pressResult == 2:
				game.showSequence()
			else:
				pass

viz.phys.enable()
viz.phys.setGravity(0,0,0)
viz.collision( viz.ON )
viz.MainView.collision(viz.OFF)
viz.callback( viz.COLLIDE_BEGIN_EVENT, onCollideBegin)
##################################################



####Graphicss Settings############################
viz.setOption("viz.antialias", "4")
viz.clearcolor(viz.SKYBLUE) 				
viz.mouse(viz.OFF)  						

light = viz.addLight()
light.position(0,0,0)
light.enable()
##################################################



####Camera########################################
viz.MainView.move(-100,160,60)
viz.MainView.lookat( [10,60,60] )
##################################################



####Game##########################################
viz.go()
game = Game()
gui = Gui(vizact, game)
##################################################



####Button########################################
buttons = []

buttons.append(SimonButton(vizact, game, 'resources/r.dae',[4,19,63], "red",game.vrsimon))
buttons.append(SimonButton(vizact, game, 'resources/g.dae',[62,19,63], "green",game.vrsimon))
buttons.append(SimonButton(vizact, game, 'resources/b.dae',[4,19,5], "blue",game.vrsimon))
buttons.append(SimonButton(vizact, game, 'resources/y.dae',[62,19,5], "yellow",game.vrsimon))
##################################################



####Hand##########################################
handShadow = projector.add( viz.add('resources/shadow.jpg') )
handShadow.setPosition(60, 75, 60, viz.ABS_GLOBAL)
handShadow.setEuler(0, 90, 0)
handShadow.enable(viz.COLLIDE_NOTIFY)
handShadow.disable(viz.DYNAMICS)
handShadow.setScale([0.60]*3)
handShadow.ortho(25, 25)

hand = handShadow.add('resources/arm.dae')
hand.setEuler(140, 0, -90)
hand.setPosition(-125, -75, 260, viz.REL_PARENT)
hand.alpha(1)

handShadow.collideMesh()
for button in buttons:
	handShadow.affect(button.vizObject)

handShadow.affect(game.vrsimon)
##################################################



##################################################

viz.mouse(viz.ON) #view control with mouse ON
sphere = hand.getBoundingSphere()
#Setup camera navigation
import vizcam
vizcam.PivotNavigate(center=[-100,160,60],distance=10)
